package com.xiaoran.springboot3.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//登录检查
@Slf4j
public class Loginterceptor implements HandlerInterceptor {

    @Override
    //处理之前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session=request.getSession();
       String url= request.getRequestURI();
        log.error("我们拦截的路径有："+url);
        Object object=session.getAttribute("LogUser");
        if(object!=null){
         return true;
        }
        //访问失败，跳转到登录页
        //session.setAttribute("msg","请先登录");
        //response.sendRedirect("/");
        request.setAttribute("msg","请先登录");
        //拿到转发器，转发到“/”,把我们原生的request和response转发过去
        request.getRequestDispatcher("/").forward(request,response);
        return false;
    }

    @Override
    //处理之前，但是快要到页面了
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    //处理之后
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
